const app = getApp();
const codeApi = require('../../../utils/codeApi.js');
Page({
  data: {
    statusOptions: ['未使用', '已使用'],
    selectedStatusIndex: 0,
    copied: false,
    usageTimes: 0,
    exportCount: 0,
    availableCount: 0,
    remainingCount: 0,
    loading: false,
    loadingMore: false,
    hasPermission: null,
    agentInfo: null,
    fromParams: {
      status: 0,
      is_exported:0,
      is_copied:0
    },
    exported: false
  },

  onLoad() {
    this.checkAgentPermission()
  },
  checkAgentPermission(callback) {
    // 确保用户ID存在
    const userId = wx.getStorageSync('userId');

    if (!userId) {
      wx.showModal({
        title: '提示',
        content: '未登录或登录已过期，请先登录',
        showCancel: false,
        success: () => {
          wx.navigateTo({
            url: '/pages/login/login'
          });
        }
      });
      return;
    }

    // 使用专用API检查权限
    codeApi.checkPermission(userId)
      .then(res => {
        if (res.code === 0 && res.data && res.data.has_permission) {
          // 保存代理信息
          this.setData({
            hasPermission: true,
            agentInfo: res.data.agent_info || {}
          });

          if (callback && typeof callback === 'function') {
            callback();
          }
        } else {
          // 没有权限
          wx.showModal({
            title: '提示',
            content: '您暂无卡密管理权限',
            showCancel: false,
            success: () => {
              wx.navigateBack();
            }
          });
        }
      })
      .catch(err => {
        console.error('检查权限失败', err);

        wx.showToast({
          title: '网络错误',
          icon: 'none',
          success: () => {
            setTimeout(() => {
              wx.navigateBack();
            }, 1500);
          }
        });
      });
  },
  onStatusChange(e) {
    this.setData({
      selectedStatusIndex: e.detail.value,
      ['fromParams.status']:e.detail.value
    });
    this.getCodesData()
  },
  onCopyChange(e) {
    this.setData({
      copied: e.detail.value,
      ['fromParams.is_copied']:e.detail.value? 1:0
    });
    this.getCodesData()
  },
  onCopyExport(e) {
    this.setData({
      ['fromParams.is_exported']:e.detail.value ? 1:0,
      exported: e.detail.value
    });
    this.getCodesData()
  },
  onUsageChange(e) {
    const usage = parseInt(e.detail.value || 0);
    this.setData({
      ['fromParams.usage_count']: usage
    })
    this.getCodesData()
  },
  onExportCountChange(e) {
    const exportCount = parseInt(e.detail.value || 0);
    const remaining = this.data.availableCount - exportCount;
    this.setData({
      exportCount,
      remainingCount: remaining >= 0 ? remaining : 0
    });
  },
  onSubmit() {
    const { availableCount, exportCount, fromParams, agentInfo } = this.data;
  
    if (availableCount <= 0) {
      wx.showToast({ title: '没有可导出的', icon: 'none' });
      return;
    }
    if (exportCount <= 0) {
      wx.showToast({ title: '请选择导出数量', icon: 'none' });
      return;
    }
    if (exportCount > availableCount) {
      wx.showToast({ title: '导出数量超过可导出数量', icon: 'none' });
      return;
    }
    if (exportCount > 200) {
      wx.showToast({ title: '导出数量上限为200条', icon: 'none' });
      return;
    }
  
    this.setData({ loading: true });
  
    const baseUrl = app.globalData.serverUrl + '/api/admin/mp/export-codes-data';
    const params = {
      ...(fromParams || {}),
      limit: exportCount,
      agent_id: agentInfo?.id
    };
  
    const query = Object.keys(params)
      .map(key => `${key}=${encodeURIComponent(params[key])}`)
      .join('&');
  
    const fullUrl = `${baseUrl}?${query}`;
  
    wx.downloadFile({
      url: fullUrl,
      success: (res) => {
        const tempFilePath = res.tempFilePath;
        console.log('临时文件路径:', tempFilePath);
  
        wx.shareFileMessage({
          filePath: tempFilePath,
          success: () => {
            wx.showToast({ title: '文件已分享' });
          },
          fail: () => {
            wx.showToast({ icon: 'none', title: '分享失败' });
          },
          complete: () => {
            this.getCodesData();
          }
        });
      },
      fail: () => {
        wx.showToast({ icon: 'none', title: '下载失败' });
        this.getCodesData();
      }
    });
  }
  ,
  getCodesData() {
    let params = this.data.fromParams
    // 添加代理ID过滤
    if (this.data.agentInfo && this.data.agentInfo.id) {
      params.agent_id = this.data.agentInfo.id;
    }

    if (!this.data.fromParams.usage_count) {
      return
    }

    // 调用激活码列表API
    codeApi.getCodes(params)
      .then(res => {
        if (res.code === 0) {
          const newData = res.data || {};
          let total = newData.total || 0;
          // 请求失败
          this.setData({
            availableCount: total,
            loadingMore: false,
            remainingCount: total - this.data.exportCount
          });

        } else {
          // 请求失败
          this.setData({
            loading: false,
            loadingMore: false
          });

          wx.showToast({
            title: res.message || '获取数据失败',
            icon: 'none'
          });

          // 停止下拉刷新
          wx.stopPullDownRefresh();
        }
      })
      .catch(err => {
        console.error('获取激活码列表失败', err);

        this.setData({
          loading: false,
          loadingMore: false
        });

        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });

        // 停止下拉刷新
        wx.stopPullDownRefresh();
      });
  },
});
